<template>
  <div class="token-status" v-if="authStore.isAuthenticated">
    <n-tooltip trigger="hover" placement="bottom">
      <template #trigger>
        <div class="status-indicator" :class="statusClass">
          <n-icon size="16" :component="TimeIcon" />
          <span class="time-text">{{ remainingTimeText }}</span>
        </div>
      </template>
      <div class="tooltip-content">
        <p><strong>登录状态：</strong>{{ statusText }}</p>
        <p><strong>登录时间：</strong>{{ loginTimeText }}</p>
        <p><strong>剩余时间：</strong>{{ remainingTimeDetail }}</p>
        <p v-if="remainingSeconds > 0"><strong>过期时间：</strong>{{ expireTimeText }}</p>
      </div>
    </n-tooltip>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { NTooltip, NIcon } from 'naive-ui'
import { TimeOutline as TimeIcon } from '@vicons/ionicons5'
import { useAuthStore } from '@/store'
import { getTokenExpiry, getWarningThresholds, formatTime, AUTH_CONFIG } from '@/config/auth'

const authStore = useAuthStore()

// 获取配置
const tokenExpiryMs = getTokenExpiry()
const warningThresholds = getWarningThresholds()

// 剩余时间（分钟）
const remainingMinutes = ref(0)
const timer = ref<number | null>(null)

// 剩余时间（秒）
const remainingSeconds = ref(0)

// 更新剩余时间
const updateRemainingTime = () => {
  if (authStore.token) {
    try {
      const tokenTime = new Date(authStore.token)
      const currentTime = new Date()
      const timeDiff = currentTime.getTime() - tokenTime.getTime()
      const remainingMs = tokenExpiryMs - timeDiff
      const remainingSecondsTotal = Math.max(0, Math.floor(remainingMs / 1000))
      
      remainingSeconds.value = remainingSecondsTotal
      remainingMinutes.value = Math.floor(remainingSecondsTotal / 60)
      
      // 如果token过期，根据配置处理过期行为
      if (remainingSecondsTotal <= 0 && AUTH_CONFIG.EXPIRY_BEHAVIOR.AUTO_REDIRECT) {
        console.log('⏰ Token expired, logging out')
        authStore.logout()
        window.location.href = AUTH_CONFIG.EXPIRY_BEHAVIOR.LOGIN_PATH
      }
    } catch (error) {
      remainingSeconds.value = 0
      remainingMinutes.value = 0
    }
  } else {
    remainingSeconds.value = 0
    remainingMinutes.value = 0
  }
}

// 状态类名 - 基于剩余秒数
const statusClass = computed(() => {
  if (remainingSeconds.value <= 0) {
    return 'expired'
  } else if (remainingSeconds.value <= warningThresholds.CRITICAL) {
    return 'warning'
  } else if (remainingSeconds.value <= warningThresholds.WARNING) {
    return 'attention'
  } else {
    return 'normal'
  }
})

// 剩余时间文本 - 显示时分秒倒计时
const remainingTimeText = computed(() => {
  return formatTime.countdown(remainingSeconds.value)
})

// 状态文本 - 基于剩余秒数
const statusText = computed(() => {
  if (remainingSeconds.value <= 0) {
    return '已过期'
  } else if (remainingSeconds.value <= warningThresholds.CRITICAL) {
    return '即将过期'
  } else if (remainingSeconds.value <= warningThresholds.WARNING) {
    return '需要注意'
  } else {
    return '正常'
  }
})

// 登录时间文本
const loginTimeText = computed(() => {
  if (!authStore.token) return '未知'
  
  try {
    const loginTime = new Date(authStore.token)
    return loginTime.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (error) {
    return '解析失败'
  }
})

// 过期时间文本
const expireTimeText = computed(() => {
  if (!authStore.token) return '未知'
  
  try {
    const loginTime = new Date(authStore.token)
    const expireTime = new Date(loginTime.getTime() + tokenExpiryMs) // 使用配置的有效期
    return expireTime.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (error) {
    return '解析失败'
  }
})

// 剩余时间详细描述
const remainingTimeDetail = computed(() => {
  return formatTime.detail(remainingSeconds.value)
})

onMounted(() => {
  // 初始更新
  updateRemainingTime()
  
  // 根据配置的间隔更新时间
  timer.value = setInterval(updateRemainingTime, AUTH_CONFIG.REFRESH_INTERVAL)
})

onUnmounted(() => {
  if (timer.value !== null) {
    clearInterval(timer.value)
  }
})
</script>

<style scoped>
.token-status {
  display: inline-flex;
  align-items: center;
  font-size: 12px;
  user-select: none;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  border-radius: 12px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.status-indicator.normal {
  background: rgba(34, 197, 94, 0.1);
  color: #22c55e;
  border: 1px solid rgba(34, 197, 94, 0.2);
}

.status-indicator.attention {
  background: rgba(251, 191, 36, 0.1);
  color: #fbbf24;
  border: 1px solid rgba(251, 191, 36, 0.2);
}

.status-indicator.warning {
  background: rgba(239, 68, 68, 0.1);
  color: #ef4444;
  border: 1px solid rgba(239, 68, 68, 0.2);
  animation: pulse-warning 2s infinite;
}

.status-indicator.expired {
  background: rgba(127, 29, 29, 0.1);
  color: #7f1d1d;
  border: 1px solid rgba(127, 29, 29, 0.2);
  animation: pulse-expired 1s infinite;
}

.time-text {
  font-weight: 500;
  white-space: nowrap;
}

.tooltip-content {
  font-size: 13px;
  line-height: 1.5;
}

.tooltip-content p {
  margin: 4px 0;
}

.tooltip-content strong {
  color: #ffffff;
}

@keyframes pulse-warning {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.8;
    transform: scale(1.02);
  }
}

@keyframes pulse-expired {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.6;
    transform: scale(1.05);
  }
}

/* 深色主题适配 */
.dark .status-indicator.normal {
  background: rgba(34, 197, 94, 0.15);
  color: #4ade80;
}

.dark .status-indicator.attention {
  background: rgba(251, 191, 36, 0.15);
  color: #fde047;
}

.dark .status-indicator.warning {
  background: rgba(239, 68, 68, 0.15);
  color: #f87171;
}

.dark .status-indicator.expired {
  background: rgba(127, 29, 29, 0.15);
  color: #dc2626;
}
</style> 